import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from 'react';
import { Button, Alert, Row, Col, Form, Tag, message, Modal } from 'antd';
import {
  ReadOutlined,
  ReloadOutlined,
  BoxPlotOutlined,
  ClockCircleOutlined,
  PlusOutlined,
  MinusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

import { setStrategyType, getStrategyType } from '@/utils/keyTypeStore';
import KeyStrategyDisplay from '@/components/KeyStrategyDisplay';
import './index.scss';

const domTracker = {
  created: 0,
  reused: 0,
  destroyed: 0,
  currentKeys: new Set(),
  reset() {
    this.created = 0;
    this.reused = 0;
    this.destroyed = 0;
    this.currentKeys.clear();
  },
 
  track(newKeys) {
    const newKeysSet = new Set(newKeys);

    let currentCreated = 0;
    let currentReused = 0;
    let currentDestroyed = 0;

   
    newKeysSet.forEach(key => {
      if (this.currentKeys.has(key)) {
        currentReused++;
      } else {
        currentCreated++;
      }
    });

   
    this.currentKeys.forEach(key => {
      if (!newKeysSet.has(key)) {
        currentDestroyed++;
      }
    });

    this.created += currentCreated;
    this.reused += currentReused;
    this.destroyed += currentDestroyed;
    this.currentKeys = newKeysSet;
  },
};

const DynamicMediumList = () => {
  const [books, setBooks] = useState([]);
  const [academicBooks, setAcademicBooks] = useState([]);
  const nextIdRef = useRef(1);
  const [renderTime, setRenderTime] = useState(null);
  const [keyType, setKeyType] = useState(getStrategyType());
  const [showAcademicTestList, setShowAcademicTestList] = useState(false);
  const [domTrackStats, setDomTrackStats] = useState({
    created: 0,
    destroyed: 0,
    reused: 0,
  });
  const [loading, setLoading] = useState(false);
  const [totalOperations, setTotalOperations] = useState(0);
  const [lastOperationTime, setLastOperationTime] = useState(0);

  const handleToggleType = value => {
    message.success({
      content: `已切换到${value}`,
    });
    setKeyType(value);
    setStrategyType(value);
  };

 
  const keyStrategy = '默认策略';

 
  const totalStock = useMemo(() => {
    return books.reduce((sum, book) => sum + book.stock, 0);
  }, [books]);

  const reuseRate = useMemo(() => {
    const N = academicBooks.length;
    if (N === 0) return '0.00';

   
   
   
   
   
   
    const totalNodes =
      domTrackStats.created + domTrackStats.reused + domTrackStats.destroyed;
    return totalNodes > 0
      ? ((domTrackStats.reused / totalNodes) * 100).toFixed(2)
      : '0.00';
  }, [academicBooks.length, domTrackStats]);

 
  useEffect(() => {
    try {
     
      const initialBooks = Array.from({ length: 100 }, () => generateBook());
      setBooks(initialBooks);
    } catch (error) {
      console.error('Error in mounted hook:', error);
      message.error('初始化库存时发生错误');
    }
  }, []);

 
  useEffect(() => {
    if (showAcademicTestList) {
      const keysToTrack = academicBooks.map(
        (book, index) => (keyType === 'id' ? book.id : index)
      );
      domTracker.track(keysToTrack);
      setDomTrackStats({
        created: domTracker.created,
        reused: domTracker.reused,
        destroyed: domTracker.destroyed,
      });
    } else {
     
      domTracker.reset();
      setDomTrackStats({ created: 0, destroyed: 0, reused: 0 });
    }
  }, [academicBooks, keyType, showAcademicTestList]);

 
  useEffect(() => {
    if (typeof window.XLSX === 'undefined') {
      const script = document.createElement('script');
      script.src =
        'https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js';
      script.async = true;
      script.onload = () => {
        console.log('XLSX library loaded successfully.');
       
       
      };
      script.onerror = () => {
        message.error('Failed to load XLSX library.');
      };
      document.head.appendChild(script);

      return () => {
       
        if (document.head.contains(script)) {
          document.head.removeChild(script);
        }
      };
    }
  }, []);

 
  const generateMockBook = useCallback(() => {
    const realTitles = [
      '百年孤独',
      '1984',
      '动物农场',
      '小王子',
      '围城',
      '活着',
      '三体',
      '人类简史',
      '情商',
      '影响力',
      '乌合之众',
      '君主论',
      '资治通鉴',
      '红楼梦',
      '西游记',
      '水浒传',
      '三国演义',
      '呐喊',
      '朝花夕拾',
      '边城',
    ];
    const realAuthors = [
      '加西亚·马尔克斯',
      '乔治·奥威尔',
      '安托万·德·圣-埃克苏佩里',
      '钱钟书',
      '余华',
      '刘慈欣',
      '尤瓦尔·赫拉利',
      '丹尼尔·戈尔曼',
      '古斯塔夫·勒庞',
      '尼科洛·马基雅维利',
      '司马光',
      '曹雪芹',
      '吴承恩',
      '施耐庵',
      '罗贯中',
      '鲁迅',
      '沈从文',
    ];
    const realPublishers = [
      '新经典文化',
      '上海译文出版社',
      '人民文学出版社',
      '北京十月文艺出版社',
      '重庆出版社',
      '中信出版集团',
      '浙江人民出版社',
      '商务印书馆',
      '译林出版社',
      '南海出版公司',
    ];
    const descriptions = [
      '本书详细介绍了相关技术原理与实践。',
      '适合初学者和进阶开发者阅读。',
      '内容涵盖理论与实战案例。',
      '帮助读者快速掌握核心知识。',
    ];
    return {
      id: nextIdRef.current++,
      title: realTitles[Math.floor(Math.random() * realTitles.length)],
      author: realAuthors[Math.floor(Math.random() * realAuthors.length)],
      status: '在架',
      expanded: false,
      isbn: '978' + Math.floor(1000000000 + Math.random() * 9000000000),
      publisher:
        realPublishers[Math.floor(Math.random() * realPublishers.length)],
      publishDate: `202${Math.floor(Math.random() * 4 + 1)}-0${Math.floor(
        Math.random() * 9 + 1
      )}-15`,
      description:
        descriptions[Math.floor(Math.random() * descriptions.length)],
      price: (Math.random() * 100 + 20).toFixed(2),
      rating: (Math.random() * 2 + 3).toFixed(1),
    };
  }, []);

  const generateBook = useCallback(() => {
    const titles = [
      '深入理解Vue.js',
      'JavaScript权威指南',
      '算法导论',
      '代码整洁之道',
      '设计模式',
      'Python编程快速上手',
      'Java核心技术',
      'MySQL必知必会',
      'Redis设计与实现',
      '计算机网络',
      '操作系统概念',
      '数据结构与算法分析',
      '编译原理',
      '软件工程',
      '人工智能基础',
      'React技术栈',
      'Node.js实战',
      'Docker容器化',
      'Kubernetes实践',
      '微服务架构',
    ];
    const authors = [
      '张明华',
      '李晓东',
      '王建国',
      '赵丽娟',
      '陈思远',
      '刘志强',
      '杨雪梅',
      '郑昊然',
    ];
    const categories = [
      '计算机技术',
      '编程语言',
      '算法与数据结构',
      '数据库',
      '网络技术',
      '人工智能',
      '软件工程',
    ];
    const statuses = ['正常', '缺货', '预警', '补货中'];
    const locations = [
      'A-01',
      'A-02',
      'B-01',
      'B-02',
      'C-01',
      'C-02',
      'D-01',
      'D-02',
    ];

    const randomNum = (min, max) =>
      Math.floor(Math.random() * (max - min + 1)) + min;
    const colors = [
      '#3498db',
      '#2ecc71',
      '#e74c3c',
      '#f1c40f',
      '#9b59b6',
      '#1abc9c',
      '#e67e22',
    ];

    return {
      id: `BOOK_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      title: titles[randomNum(0, titles.length - 1)],
      author: authors[randomNum(0, authors.length - 1)],
      category: categories[randomNum(0, categories.length - 1)],
      status: statuses[randomNum(0, statuses.length - 1)],
      stock: randomNum(0, 100),
      location: locations[randomNum(0, locations.length - 1)],
      isbn: `978${randomNum(1000000000, 9999999999)}`,
      coverColor: colors[randomNum(0, colors.length - 1)],
    };
  }, []);

  const generateBooks = useCallback(
    (count = 10) => {
      const startTime = performance.now();
      setBooks(Array.from({ length: count }, () => generateBook()));
      setTotalOperations(prev => prev + 1);
      setLastOperationTime((performance.now() - startTime).toFixed(2));
    },
    [generateBook]
  );

  const sortBooks = useCallback(() => {
    const startTime = performance.now();
    setBooks(prevBooks => {
      const sorted = [...prevBooks].sort((a, b) => {
        if (a.category !== b.category) {
          return a.category.localeCompare(b.category);
        }
        if (a.author !== b.author) {
          return a.author.localeCompare(b.author);
        }
        return a.title.localeCompare(b.title);
      });
      return sorted;
    });
    setTotalOperations(prev => prev + 1);
    setLastOperationTime((performance.now() - startTime).toFixed(2));
  }, []);

  const insertRandomBook = useCallback(() => {
    const startTime = performance.now();
    setBooks(prevBooks => {
      const randomIndex = Math.floor(Math.random() * (prevBooks.length + 1));
      const newBook = generateBook();
      const newBooks = [...prevBooks];
      newBooks.splice(randomIndex, 0, newBook);
      return newBooks;
    });
    setTotalOperations(prev => prev + 1);
    setLastOperationTime((performance.now() - startTime).toFixed(2));
  }, [generateBook]);

  const deleteRandomBook = useCallback(() => {
    setBooks(prevBooks => {
      if (prevBooks.length === 0) return prevBooks;
      const startTime = performance.now();
      const randomIndex = Math.floor(Math.random() * prevBooks.length);
      const newBooks = [...prevBooks];
      newBooks.splice(randomIndex, 1);
      setTotalOperations(prev => prev + 1);
      setLastOperationTime((performance.now() - startTime).toFixed(2));
      return newBooks;
    });
  }, []);

  const replaceAllBooks = useCallback(() => {
    const startTime = performance.now();
    setBooks(prevBooks => {
      const len = prevBooks.length > 0 ? prevBooks.length : 10;
      return Array.from({ length: len }, () => generateBook());
    });
    setTotalOperations(prev => prev + 1);
    setLastOperationTime((performance.now() - startTime).toFixed(2));
  }, [generateBook]);

  const addBook = useCallback(() => {
    const newBook = generateBook();
    setBooks(prevBooks => [newBook, ...prevBooks]);
    setTotalOperations(prev => prev + 1);
  }, [generateBook]);

  const removeBook = useCallback(bookId => {
    setBooks(prevBooks => {
      const newBooks = prevBooks.filter(book => book.id !== bookId);
      if (newBooks.length < prevBooks.length) {
        setTotalOperations(prev => prev + 1);
      }
      return newBooks;
    });
  }, []);

  const increaseStock = useCallback(bookId => {
    setBooks(prevBooks =>
      prevBooks.map(book => {
        if (book.id === bookId) {
          setTotalOperations(prev => prev + 1);
          const newStock = book.stock + 1;
          let newStatus = book.status;
          if (newStock > 10) {
            newStatus = '正常';
          } else if (newStock > 5) {
            newStatus = '预警';
          } else if (newStock > 0) {
            newStatus = '缺货';
          }
          return { ...book, stock: newStock, status: newStatus };
        }
        return book;
      })
    );
  }, []);

  const decreaseStock = useCallback(bookId => {
    setBooks(prevBooks =>
      prevBooks.map(book => {
        if (book.id === bookId && book.stock > 0) {
          setTotalOperations(prev => prev + 1);
          const newStock = book.stock - 1;
          let newStatus = book.status;
          if (newStock === 0) {
            newStatus = '缺货';
          } else if (newStock <= 5) {
            newStatus = '预警';
          }
          return { ...book, stock: newStock, status: newStatus };
        }
        return book;
      })
    );
  }, []);

  const initStock = useCallback(() => {
    setBooks(Array.from({ length: 10 }).map(() => generateBook()));
  }, [generateBook]);

  const clearStock = useCallback(() => {
    setBooks(prevBooks =>
      prevBooks.map(book => ({ ...book, stock: 0, status: '缺货' }))
    );
  }, []);

  const getStockClass = useCallback(stock => {
    if (stock === 0) return 'text-red-500';
    if (stock < 10) return 'text-yellow-500';
    return 'text-green-500';
  }, []);

  const getStatusType = useCallback(status => {
    switch (status) {
      case '正常':
        return 'success';
      case '缺货':
        return 'error';
      case '预警':
        return 'warning';
      case '补货中':
        return 'processing';
      default:
        return 'default';
    }
  }, []);

  const sleep = useCallback(ms => {
    return new Promise(resolve => setTimeout(resolve, ms));
  }, []);

  const preciseMeasure = useCallback(async operationFn => {
    return new Promise(resolve => {
      requestAnimationFrame(() => {
        performance.clearMarks();
        performance.clearMeasures();
        performance.mark('op-start');

        operationFn();

       
        requestAnimationFrame(() => {
          performance.mark('op-end');
          performance.measure('op-duration', 'op-start', 'op-end');
          const measures = performance.getEntriesByName('op-duration');
          const duration =
            measures.length > 0 ? measures[0].duration.toFixed(2) : '0.00';
          setRenderTime(duration);
          resolve(duration);
        });
      });
    });
  }, []);

  const generateAcademicBooks = useCallback(
    count => {
      nextIdRef.current = 1;
      setAcademicBooks(Array.from({ length: count }, () => generateMockBook()));
    },
    [generateMockBook]
  );

  const insertRandomAcademicBook = useCallback(() => {
    setAcademicBooks(prevBooks => {
      const randomIndex = Math.floor(Math.random() * (prevBooks.length + 1));
      const newBook = generateMockBook();
      const newBooks = [...prevBooks];
      newBooks.splice(randomIndex, 0, newBook);
      return newBooks;
    });
  }, [generateMockBook]);

  const deleteRandomAcademicBook = useCallback(() => {
    setAcademicBooks(prevBooks => {
      if (prevBooks.length === 0) return prevBooks;
      const randomIndex = Math.floor(Math.random() * prevBooks.length);
      const newBooks = [...prevBooks];
      newBooks.splice(randomIndex, 1);
      return newBooks;
    });
  }, []);

  const shuffleAcademicBooks = useCallback(() => {
    setAcademicBooks(prevBooks => {
      const arr = [...prevBooks];
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
      return arr;
    });
  }, []);

  const replaceAllAcademicBooks = useCallback(() => {
    setAcademicBooks(prevBooks => {
      const len = prevBooks.length > 0 ? prevBooks.length : 100;
      return Array.from({ length: len }, () => generateMockBook());
    });
  }, [generateMockBook]);

  const appendToEndAcademicBook = useCallback(() => {
    setAcademicBooks(prevBooks => [...prevBooks, generateMockBook()]);
  }, [generateMockBook]);

  const insertToMiddleAcademicBook = useCallback(() => {
    setAcademicBooks(prevBooks => {
      const mid = Math.floor(prevBooks.length / 2);
      const newBook = generateMockBook();
      const newBooks = [...prevBooks];
      newBooks.splice(mid, 0, newBook);
      return newBooks;
    });
  }, [generateMockBook]);

  const partialUpdateAcademicBook = useCallback(() => {
    setAcademicBooks(prevBooks => {
      if (prevBooks.length === 0) return prevBooks;
      const idx = Math.floor(Math.random() * prevBooks.length);
      const newBooks = [...prevBooks];
      newBooks[idx] = {
        ...newBooks[idx],
        title: newBooks[idx].title + '_更新',
      };
      return newBooks;
    });
  }, []);

  const performAcademicBookOperationAndMeasure = useCallback(
    async (keyTypeParam, operationName, operationFn) => {
      console.log(
        `performAcademicBookOperationAndMeasure: Starting test for KeyType: ${keyTypeParam}, Operation: ${operationName}`
      );

      setKeyType(keyTypeParam);
      setShowAcademicTestList(true);
      setRenderTime(null);

     
      domTracker.reset();
      setDomTrackStats({ created: 0, destroyed: 0, reused: 0 });

      const totalTimeStart = performance.now();

     
      if (!operationName.startsWith('生成')) {
        await preciseMeasure(() => generateAcademicBooks(500));
        await sleep(50);
        domTracker.reset();
      }

      const initialCreated = domTracker.created;
      const initialDestroyed = domTracker.destroyed;

      const renderDuration = await preciseMeasure(operationFn);

      const totalTime = (performance.now() - totalTimeStart).toFixed(2);

      const finalCreated = domTracker.created;
      const finalDestroyed = domTracker.destroyed;

      const createdCount = finalCreated - initialCreated;
      const destroyedCount = finalDestroyed - initialDestroyed;
      const currentAcademicListLength = academicBooks.length;
      const reusedCount = currentAcademicListLength - destroyedCount;

      const totalElementsProcessed =
        createdCount + reusedCount + destroyedCount;
      const reuseRatePercentage =
        totalElementsProcessed > 0
          ? ((reusedCount / totalElementsProcessed) * 100).toFixed(2)
          : '0.00';

      return {
        测试类型: keyTypeParam,
        操作类型: operationName,
        '渲染时间(ms)': renderDuration,
        '总耗时(ms)': totalTime,
        DOM创建数: createdCount,
        DOM复用数: reusedCount,
        DOM销毁数: destroyedCount,
        'DOM复用率(%)': reuseRatePercentage,
        列表项数量: currentAcademicListLength,
        测试时间: new Date().toLocaleString(),
      };
    },
    [academicBooks, generateAcademicBooks, preciseMeasure, sleep]
  );

  const autoTestReuse = useCallback(async () => {
    message.info('开始自动测试复用（单次）...');
    setShowAcademicTestList(true);

   
    domTracker.reset();
    setDomTrackStats({ created: 0, destroyed: 0, reused: 0 });

   
    await preciseMeasure(() => generateAcademicBooks(100));
    await sleep(100);

    const initialCreated = domTracker.created;
    const initialDestroyed = domTracker.destroyed;
    domTracker.reset();

   
    let operationFn;
    let operationName;
    if (keyType === 'id') {
      operationFn = shuffleAcademicBooks;
      operationName = '打乱顺序';
    } else {
     
      operationFn = () =>
        setAcademicBooks(
          Array.from({ length: academicBooks.length }, (_, idx) =>
            generateMockBook()
          )
        );
      operationName = '替换所有（非ID Key）';
    }

    const renderDuration = await preciseMeasure(operationFn);
    await sleep(500);

    const finalCreated = domTracker.created;
    const finalDestroyed = domTracker.destroyed;

    const createdDuringOperation = finalCreated - initialCreated;
    const destroyedDuringOperation = finalDestroyed - initialDestroyed;

    const N = academicBooks.length;
    const reusedCalculated = N - destroyedDuringOperation;

    const totalElementsProcessed =
      createdDuringOperation + reusedCalculated + destroyedDuringOperation;
    const reuseRatePercentageCalculated =
      totalElementsProcessed > 0
        ? ((reusedCalculated / totalElementsProcessed) * 100).toFixed(2)
        : '0.00';

    const stats = {
      created: createdDuringOperation,
      reused: reusedCalculated,
      destroyed: destroyedDuringOperation,
      reuseRate: reuseRatePercentageCalculated,
      totalItems: N,
    };

    setDomTrackStats({
      created: createdDuringOperation,
      reused: reusedCalculated,
      destroyed: destroyedDuringOperation,
    });

    message.success(
      `单次测试完成，渲染耗时: ${renderDuration}ms, 复用率: ${reuseRatePercentageCalculated}%`
    );
    setShowAcademicTestList(false);
  }, [
    academicBooks,
    generateAcademicBooks,
    generateMockBook,
    keyType,
    preciseMeasure,
    shuffleAcademicBooks,
    sleep,
  ]);

  const autoTestBatchAndExportExcel = useCallback(async () => {
    if (typeof window.XLSX === 'undefined') {
      message.error('XLSX 库尚未加载，请稍候再试。');
      return;
    }

    message.info('开始批量测试并导出Excel...');
    setLoading(true);
    const testCases = [
      { name: 'ID作为Key', keyType: 'id' },
      { name: 'Index作为Key', keyType: 'index' },
      { name: '无Key', keyType: 'none' },
    ];

    const results = [];
    const operations = [
      {
        name: '生成100本',
        fn: (count = 100) => generateAcademicBooks(count),
        isGenerate: true,
      },
      {
        name: '生成1000本',
        fn: (count = 1000) => generateAcademicBooks(count),
        isGenerate: true,
      },
      { name: '打乱顺序', fn: shuffleAcademicBooks, isGenerate: false },
      { name: '插入元素', fn: insertRandomAcademicBook, isGenerate: false },
      { name: '删除元素', fn: deleteRandomAcademicBook, isGenerate: false },
      { name: '替换所有', fn: replaceAllAcademicBooks, isGenerate: false },
      { name: '尾部追加', fn: appendToEndAcademicBook, isGenerate: false },
      { name: '中间插入', fn: insertToMiddleAcademicBook, isGenerate: false },
      { name: '局部更新', fn: partialUpdateAcademicBook, isGenerate: false },
    ];

    for (const testCase of testCases) {
      message.info(`开始测试: ${testCase.name}`);

      for (const operation of operations) {
       
        const opFn = operation.isGenerate
          ? () => operation.fn(parseFloat(operation.name.replace('生成', '')))
          : operation.fn;
        const data = await performAcademicBookOperationAndMeasure(
          testCase.keyType,
          operation.name,
          opFn
        );

        results.push(data);
        await sleep(500);
      }
    }

    const wb = window.XLSX.utils.book_new();
    const ws = window.XLSX.utils.json_to_sheet(results);

    const colWidths = [
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 20 },
    ];
    ws['!cols'] = colWidths;

    window.XLSX.utils.book_append_sheet(wb, ws, 'DOM性能测试结果');

    const fileName = `DOM性能测试结果_${new Date()
      .toISOString()
      .slice(0, 19)
      .replace(/[:]/g, '-')}.xlsx`;
    window.XLSX.writeFile(wb, fileName);

    message.success('测试完成，数据已导出到Excel文件');
    setLoading(false);
    setShowAcademicTestList(false);
  }, [
    generateAcademicBooks,
    shuffleAcademicBooks,
    insertRandomAcademicBook,
    deleteRandomAcademicBook,
    replaceAllAcademicBooks,
    appendToEndAcademicBook,
    insertToMiddleAcademicBook,
    partialUpdateAcademicBook,
    performAcademicBookOperationAndMeasure,
    sleep,
  ]);

  const exportReuseStatsToExcel = useCallback(() => {
    if (typeof window.XLSX === 'undefined') {
      message.error('XLSX 库尚未加载，请稍候再试。');
      return;
    }

    const stats = [
      {
        DOM创建数: domTrackStats.created,
        DOM复用数: domTrackStats.reused,
        DOM销毁数: domTrackStats.destroyed,
        'DOM复用率(%)': reuseRate + '%',
        列表项数量: academicBooks.length,
        测试时间: new Date().toLocaleString(),
      },
    ];

    const ws = window.XLSX.utils.json_to_sheet(stats);
    const wb = window.XLSX.utils.book_new();
    window.XLSX.utils.book_append_sheet(wb, ws, '复用统计');
    window.XLSX.writeFile(wb, `reuse-stats-${Date.now()}.xlsx`);
    message.success('统计数据已导出为Excel！');
  }, [domTrackStats, academicBooks.length, reuseRate]);

  return (
    <div className='p-6 bg-gray-50 min-h-screen font-sans text-gray-800'>
      <div className='dynamic-list-container'>
        <div className='dynamic-list'>
          <div className='page-header flex justify-between items-center mb-6'>
            <div className='left-section'>
              <h1 className='page-heading'>
                图书目录
              </h1>
              <KeyStrategyDisplay />
            </div>
            <div className='right-section flex space-x-2'>
              <Button
                type='primary'
                onClick={sortBooks}
                className='rounded-md shadow-sm bg-green-500 hover:bg-green-600 border-green-500 hover:border-green-600'
              >
                打乱顺序
              </Button>
              <Button
                type='primary'
                onClick={insertRandomBook}
                className='rounded-md shadow-sm bg-yellow-500 hover:bg-yellow-600 border-yellow-500 hover:border-yellow-600'
              >
                插入随机图书
              </Button>
              <Button
                type='primary'
                danger
                onClick={deleteRandomBook}
                className='rounded-md shadow-sm'
              >
                删除随机图书
              </Button>
              <Button
                type='primary'
                onClick={replaceAllBooks}
                className='rounded-md shadow-sm bg-blue-500 hover:bg-blue-600 border-blue-500 hover:border-blue-600'
              >
                替换所有图书
              </Button>
            </div>
          </div>
        </div>

        <div className='description mb-6'>
          <Alert
            message='模块说明'
            description='库存管理系统用于实时跟踪图书馆图书的库存变化。支持入库、出库、调拨等操作，采用Vue.js Key绑定策略优化动态数据更新的性能表现。'
            type='info'
            showIcon
            closable={false}
            className='rounded-lg shadow-sm'
          />
        </div>

        <div className='status-summary mb-6'>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <div className='status-card bg-white p-4 rounded-lg shadow-md flex items-center space-x-4'>
                <div className='status-icon total p-3 rounded-full bg-blue-100 text-blue-600 text-2xl'>
                  <ReadOutlined />
                </div>
                <div className='status-info'>
                  <h3 className='text-2xl font-bold text-gray-800'>
                    {books.length}
                  </h3>
                  <p className='text-gray-500 text-sm'>总图书数</p>
                </div>
              </div>
            </Col>
            <Col span={6}>
              <div className='status-card bg-white p-4 rounded-lg shadow-md flex items-center space-x-4'>
                <div className='status-icon operations p-3 rounded-full bg-green-100 text-green-600 text-2xl'>
                  <ReloadOutlined />
                </div>
                <div className='status-info'>
                  <h3 className='text-2xl font-bold text-gray-800'>
                    {totalOperations}
                  </h3>
                  <p className='text-gray-500 text-sm'>操作次数</p>
                </div>
              </div>
            </Col>
            <Col span={6}>
              <div className='status-card bg-white p-4 rounded-lg shadow-md flex items-center space-x-4'>
                <div className='status-icon stock p-3 rounded-full bg-purple-100 text-purple-600 text-2xl'>
                  <BoxPlotOutlined />
                </div>
                <div className='status-info'>
                  <h3 className='text-2xl font-bold text-gray-800'>
                    {totalStock}
                  </h3>
                  <p className='text-gray-500 text-sm'>总库存</p>
                </div>
              </div>
            </Col>
            <Col span={6}>
              <div className='status-card bg-white p-4 rounded-lg shadow-md flex items-center space-x-4'>
                <div className='status-icon time p-3 rounded-full bg-orange-100 text-orange-600 text-2xl'>
                  <ClockCircleOutlined />
                </div>
                <div className='status-info'>
                  <h3 className='text-2xl font-bold text-gray-800'>
                    {lastOperationTime}ms
                  </h3>
                  <p className='text-gray-500 text-sm'>最后操作耗时</p>
                </div>
              </div>
            </Col>
          </Row>
        </div>

        <div className='control-panel bg-white p-6 rounded-lg shadow-md mb-6'>
          <Form layout='vertical' className='space-y-4'>
            <Form.Item
              label={
                <span className='text-lg font-semibold text-gray-700'>
                  快速操作
                </span>
              }
              className='mb-0'
            >
              <div className='flex flex-wrap gap-2'>
                <Button
                  type='primary'
                  size='middle'
                  onClick={addBook}
                  loading={loading}
                  className='rounded-md shadow-sm bg-green-500 hover:bg-green-600 border-green-500 hover:border-green-600'
                >
                  <PlusOutlined /> 入库图书
                </Button>
                <Button
                  type='primary'
                  size='middle'
                  onClick={initStock}
                  loading={loading}
                  className='rounded-md shadow-sm'
                >
                  <ReloadOutlined /> 初始化库存
                </Button>
                <Button
                  type='primary'
                  size='middle'
                  onClick={clearStock}
                  loading={loading}
                  danger
                  className='rounded-md shadow-sm'
                >
                  <DeleteOutlined /> 清空库存
                </Button>
              </div>
            </Form.Item>

            <Form.Item
              label={
                <span className='text-lg font-semibold text-gray-700'>
                  性能测试操作
                </span>
              }
              className='mb-0'
            >
              <div className='flex flex-wrap gap-2'>
                <Button
                  type={keyType === 'id' ? 'primary' : 'default'}
                  onClick={() => handleToggleType('id')}
                >
                  ID作为Key
                </Button>
                <Button
                  type={keyType === 'index' ? 'primary' : 'default'}
                  onClick={() => handleToggleType('index')}
                >
                  Index作为Key
                </Button>
                <Button
                  type={keyType === 'none' ? 'primary' : 'default'}
                  onClick={() => handleToggleType('none')}
                >
                  无Key
                </Button>
                <Button
                  type='primary'
                  size='middle'
                  onClick={() => generateAcademicBooks(1000)}
                  className='rounded-md shadow-sm'
                >
                  生成1000项
                </Button>
                <Button
                  color='orange'
                  variant='solid'
                  onClick={insertRandomAcademicBook}
                  className='rounded-md shadow-sm'
                >
                  插入元素
                </Button>
                <Button
                  color='danger'
                  variant='solid'
                  onClick={deleteRandomAcademicBook}
                  className='rounded-md shadow-sm'
                >
                  删除元素
                </Button>
                <Button
                  color='green'
                  variant='solid'
                  onClick={shuffleAcademicBooks}
                  className='rounded-md shadow-sm'
                >
                  打乱顺序
                </Button>
                <Button
                  color='primary'
                  variant='solid'
                  onClick={replaceAllAcademicBooks}
                  className='rounded-md shadow-sm'
                >
                  替换所有
                </Button>
                <Button
                  color='orange'
                  variant='solid'
                  onClick={appendToEndAcademicBook}
                  className='rounded-md shadow-sm'
                >
                  尾部追加
                </Button>
                <Button
                  color='danger'
                  variant='solid'
                  onClick={insertToMiddleAcademicBook}
                  className='rounded-md shadow-sm'
                >
                  中间插入
                </Button>
                <Button
                  color='green'
                  variant='solid'
                  onClick={partialUpdateAcademicBook}
                  className='rounded-md shadow-sm'
                >
                  局部更新
                </Button>
                <Button
                  color='primary'
                  variant='solid'
                  onClick={autoTestReuse}
                  className='rounded-md shadow-sm'
                >
                  自动测试复用（单次）
                </Button>
                <Button
                  color='orange'
                  variant='solid'
                  onClick={autoTestBatchAndExportExcel}
                  loading={loading}
                  className='rounded-md shadow-sm'
                >
                  批量测试并导出Excel
                </Button>
                <Button
                  color='danger'
                  variant='solid'
                  onClick={exportReuseStatsToExcel}
                  className='rounded-md shadow-sm'
                >
                  导出Excel（当前）
                </Button>
              </div>
            </Form.Item>
          </Form>
        </div>

        <div className='performance-metrics mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg shadow-sm'>
          <h3 className='text-xl font-semibold text-blue-600 mb-3'>性能指标</h3>
          <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4'>
            <div className='metric-item'>
              <span className='metric-label text-gray-600'>渲染时间：</span>
              <span className='metric-value font-bold text-orange-600'>
                {renderTime || '0'} ms
              </span>
            </div>
            <div className='metric-item'>
              <span className='metric-label text-gray-600'>DOM创建数：</span>
              <span className='metric-value font-bold text-blue-600'>
                {domTrackStats.created || 0}
              </span>
            </div>
            <div className='metric-item'>
              <span className='metric-label text-gray-600'>DOM复用数：</span>
              <span className='metric-value font-bold text-green-600'>
                {domTrackStats.reused || 0}
              </span>
            </div>
            <div className='metric-item'>
              <span className='metric-label text-gray-600'>DOM销毁数：</span>
              <span className='metric-value font-bold text-red-600'>
                {domTrackStats.destroyed || 0}
              </span>
            </div>
            <div className='metric-item'>
              <span className='metric-label text-gray-600'>DOM复用率：</span>
              <span className='metric-value font-bold text-gray-700'>
                {reuseRate}%
              </span>
            </div>
          </div>
        </div>
        {renderTime && (
          <div className='mb-3 text-orange-600 font-bold'>
            本次渲染耗时：{renderTime} ms
            <br />
            节点创建：{domTrackStats.created}，复用：{domTrackStats.reused}
            ，销毁：{domTrackStats.destroyed}，复用率：{reuseRate}%
          </div>
        )}

        {/* 用于学术数据测试的纯粹列表，确保能准确捕获created和destroyed */}
        {showAcademicTestList && (
          <div className='academic-test-list flex flex-wrap gap-1 mb-6 border p-2 rounded-md bg-white shadow-sm'>
            {academicBooks.map((book, index) => (
              <span
                key={keyType === 'id' ? book.id : index}
                data-id={book.id}
                className='p-1 border border-gray-200 rounded-sm text-xs'
              >
                {book.title}
              </span>
            ))}
          </div>
        )}

        {books.length > 0 ? (
          <div className='book-list  gap-4'>
            {/* TransitionGroup is complex in React, omitted for core functionality. */}
            {books.map(book => (
              <div
                key={book.id}
                className='book-item bg-white p-4 rounded-lg shadow-md flex items-center space-x-4 transition-all duration-300 ease-in-out hover:shadow-lg'
              >
                <div
                  className='book-cover flex-shrink-0 w-16 h-16 rounded-lg flex items-center justify-center text-white text-3xl'
                  style={{ backgroundColor: book.coverColor }}
                >
                  <ReadOutlined />
                </div>
                <div className='book-info flex-grow'>
                  <div className='book-title text-lg font-semibold text-gray-900 truncate'>
                    {book.title}
                  </div>
                  <div className='book-meta text-gray-600 text-sm'>
                    <span className='author mr-2'>{book.author}</span>
                    <span className='category'>{book.category}</span>
                  </div>
                  <div className='book-details text-gray-500 text-xs mt-1'>
                    <span className='isbn mr-2'>ISBN: {book.isbn}</span>
                    <span className='location'>位置: {book.location}</span>
                  </div>
                </div>
                <div className='stock-info flex-shrink-0 text-right'>
                  <div className='stock-count text-sm'>
                    <span className='label text-gray-500'>库存:</span>
                    <span
                      className={`count text-xl font-bold ml-1 ${getStockClass(
                        book.stock
                      )}`}
                    >
                      {book.stock}
                    </span>
                  </div>
                  <div className='stock-status mt-1'>
                    <Tag
                      color={getStatusType(book.status)}
                      className='rounded-md px-1 py-0.5 text-xs'
                    >
                      {book.status}
                    </Tag>
                  </div>
                </div>
                <div className='operations flex-shrink-0 flex '>
                  <Button
                    size='small'
                    type='primary'
                    onClick={() => increaseStock(book.id)}
                    className='rounded-md shadow-sm bg-green-500 hover:bg-green-600 border-green-500 hover:border-green-600'
                  >
                    <PlusOutlined />
                  </Button>
                  <Button
                    size='small'
                    type='primary'
                    onClick={() => decreaseStock(book.id)}
                    disabled={book.stock <= 0}
                    className='rounded-md shadow-sm bg-yellow-500 hover:bg-yellow-600 border-yellow-500 hover:border-yellow-600'
                  >
                    <MinusOutlined />
                  </Button>
                  <Button
                    size='small'
                    type='primary'
                    danger
                    onClick={() => removeBook(book.id)}
                    className='rounded-md shadow-sm'
                  >
                    <DeleteOutlined />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className='empty-state bg-white p-8 rounded-lg shadow-md text-center flex flex-col items-center justify-center min-h-[300px]'>
            <div className='empty-icon text-gray-400 text-6xl mb-4'>
              <BoxPlotOutlined />
            </div>
            <h3 className='text-2xl font-semibold text-gray-700 mb-2'>
              库存为空
            </h3>
            <p className='text-gray-500 mb-4'>
              当前没有图书库存记录，点击"初始化库存"开始管理
            </p>
            <Button
              type='primary'
              onClick={initStock}
              loading={loading}
              className='rounded-md shadow-sm'
            >
              初始化库存
            </Button>
          </div>
        )}

        {/* PerformancePanel is not provided in original, omitted for now */}
        {/* <performance-panel ref="perfPanel" /> */}
      </div>
    </div>
  );
};

export default DynamicMediumList;
